package com.wowangz.cms.systemmanage.province.api;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.wowangz.cms.common.pojo.AjaxDataEntity;
import com.wowangz.cms.common.utils.SysConstant;
import com.wowangz.cms.component.datagrid.pojo.DataGrid;
import com.wowangz.cms.component.datagrid.pojo.DataResult;
import com.wowangz.cms.component.datagrid.pojo.DataStyle;
import com.wowangz.cms.component.datagrid.pojo.PangingParam;
import com.wowangz.cms.component.datagrid.utils.DataTypeConstant;
import com.wowangz.cms.component.datagrid.utils.PangingTools;
import com.wowangz.cms.syscore.IssTransactionContainer;
import com.wowangz.cms.syscore.api.BaseController;
import com.wowangz.cms.syscore.api.JSONFactory;
import com.wowangz.cms.syscore.utils.MessageResourcesUtils;
import com.wowangz.cms.syscore.utils.ServletUtils;
import com.wowangz.cms.systemmanage.city.pojo.City;
import com.wowangz.cms.systemmanage.city.service.CityService;
import com.wowangz.cms.systemmanage.province.pojo.Province;
import com.wowangz.cms.systemmanage.province.service.ProvinceService;


@Scope("prototype")
@Controller
public class ProvinceController extends BaseController{

	private static Logger logger = LoggerFactory.getLogger(ProvinceController.class);
	
	/**
	 * 点击菜单"省信息管理"显示“省信息管理”列表
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/province/queryProvinceList.web")
	public String queryProvinceList(HttpServletRequest request, HttpServletResponse response, Model model) {
		
		return "/WEB-INF/jsp/systemmanage/province/provinceList";
	}
	
	/**
	 * 打开“省信息管理”列表加载列表数据
	 * @param request
	 * @param response
	 * @param model
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/systemmanage/province/queryProvinceListInfoDataGrid.json")
	public void queryProvinceListInfoDataGrid(HttpServletRequest request, HttpServletResponse response, Model model) {

		PangingParam pangingParam = null;
		DataResult dataResult = new DataResult();
		DataGrid dataGrid = null;

		try {
			pangingParam = (PangingParam) ServletUtils.getParametersToBaseEntity(request, PangingParam.class);
			HashMap<String, Object> map = (HashMap) ServletUtils.getParametersToHashMap(request);
			dataGrid = new DataGrid();
			dataGrid.setPangingParam(pangingParam);

			map.put("startrow", dataGrid.getStartrow());
			map.put("endrow", dataGrid.getEndrow());
			map.put("rows", dataGrid.getRows());
			map.put("sort", dataGrid.getSort());
			map.put("order", dataGrid.getOrder());
			map.put("statusid", SysConstant.RecordStatus.VALID);

			ProvinceService provinceService = (ProvinceService) IssTransactionContainer.getInstance(ProvinceService.class, false);
			long resultCount = provinceService.findResultCount(map);
			List<Province> resultList = provinceService.findResultList(map);

			DataStyle dataStyle = new DataStyle();
			dataStyle.setPageIndex(pangingParam.getPage());
			dataStyle.setDataCount(resultCount);
			dataStyle.setDataList(resultList);

			dataStyle.addDepict("id", DataTypeConstant.LONG);
			dataStyle.addDepict("provincecode", DataTypeConstant.STRING);
			dataStyle.addDepict("provincename", DataTypeConstant.STRING);
			dataStyle.addDepict("provincedesc", DataTypeConstant.STRING);
			dataStyle.addDepict("branchunitecode", DataTypeConstant.LONG);
			dataResult = PangingTools.buildResultPagerInfo(dataStyle);

			if (pangingParam.getReportExportType() == 0) {
				response.getWriter().write(JSONFactory.toJSONString(dataResult, userContext));
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 跳转省信息添加页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/province/toAddProvince.web")
	public String toAddProvince(HttpServletRequest request, HttpServletResponse response, Model model) {
		return "/WEB-INF/jsp/systemmanage/province/provinceAdd";
	}
	
	/**
	 * 新增省信息
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/province/addProvince.web", method = { RequestMethod.GET, RequestMethod.POST })
	public String addProvince(HttpServletRequest request, HttpServletResponse response, Model model) {
		Province province = null;
		try {
			province = (Province) ServletUtils.getParametersToBaseEntity(request, Province.class);
			province.setInputtime(new Date());
			province.setInputuserid(userContext.getLoginUser().getId());
			province.setModifytime(new Date());
			province.setModifyuserid(userContext.getLoginUser().getId());
			province.setStatusid(SysConstant.RecordStatus.VALID);
			ProvinceService provinceService = (ProvinceService) IssTransactionContainer.getInstance(ProvinceService.class, true);
			
			provinceService.add(province);
			userContext.setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert1"));
			userContext.setCloseWindow(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/WEB-INF/jsp/systemmanage/province/provinceAdd";
	}
	
	@RequestMapping(value = "/systemmanage/province/validattionProvince.json", method = { RequestMethod.GET, RequestMethod.POST })
	public void validattionProvince(HttpServletRequest request, HttpServletResponse response, Model model) {
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		try {
			Province province = null;
			StringBuffer errorMsg = new StringBuffer();
			HashMap<String, Object> map = new HashMap<String, Object>();
			province = (Province) ServletUtils.getParametersToBaseEntity(request, Province.class);
			
			ProvinceService provinceService = (ProvinceService) IssTransactionContainer.getInstance(ProvinceService.class, false);
			map.put("statusid", SysConstant.RecordStatus.VALID);
			if(null != province.getId()){
				map.put("id", province.getId());
			}
			map.put("provincecode", province.getProvincecode());
			if(!provinceService.validationProvince(map)){
				errorMsg.append(MessageResourcesUtils.getMessage(request, "systemmanage.province.provinceAdd.alert1")+"！\n");
			}
			map.remove("provincecode");
			map.put("provincename", province.getProvincename());
			if(!provinceService.validationProvince(map)){
				errorMsg.append(MessageResourcesUtils.getMessage(request, "systemmanage.province.provinceAdd.alert2")+"！\n");
			}
			map.remove("provincename");
			
			if(StringUtils.isNotEmpty(errorMsg.toString())){
				userContext.setErrorMessage(errorMsg.toString());
			}
			response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, userContext));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 跳转修改省信息页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/province/toUpdateProvince.web")
	public String toUpdateProvince(HttpServletRequest request, HttpServletResponse response, Model model) {
		try {
			String provinceId = getRequest().getParameter("id");
			ProvinceService provinceService = (ProvinceService) IssTransactionContainer.getInstance(ProvinceService.class, false);
			Province province = provinceService.findProvinceById(provinceId);
			model.addAttribute("province", province);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/WEB-INF/jsp/systemmanage/province/provinceUpdate";
	}
	
	/**
	 * 修改省信息
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/province/updateProvince.web", method = { RequestMethod.GET, RequestMethod.POST })
	public String updateProvince(HttpServletRequest request, HttpServletResponse response, Model model) {
		Province province = null;
		try {
			province = (Province) ServletUtils.getParametersToBaseEntity(request, Province.class);
			province.setModifytime(new Date());
			ProvinceService provinceService = (ProvinceService) IssTransactionContainer.getInstance(ProvinceService.class, true);
			provinceService.update(province);
			userContext.setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert1"));
			userContext.setCloseWindow(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/WEB-INF/jsp/systemmanage/province/provinceUpdate";
	}
	
	/**
	 * 删除的省信息
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "/systemmanage/province/deleteProvince.json", method = { RequestMethod.GET, RequestMethod.POST })
	public void deleteProvince(HttpServletRequest request, HttpServletResponse response, Model model) {
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		try {
			Long provinceId = Long.valueOf(getRequest().getParameter("id"));
			CityService cityService = (CityService) IssTransactionContainer.getInstance(CityService.class, true);
			List<City> list = cityService.findCityByProvinceId(provinceId);
			if(list == null || list.size() == 0){
				Province province = new Province();
				province.setId(provinceId);
				province.setStatusid(SysConstant.RecordStatus.INVALID);
				ProvinceService provinceService = (ProvinceService) IssTransactionContainer.getInstance(ProvinceService.class, false);
				provinceService.update(province);
				userContext.setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert3"));
			}else{
				userContext.setInfoMessage(MessageResourcesUtils.getMessage(request, "systemmanage.province.provinceList.alert1"));
			}
			response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, userContext));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
